import java.util.*;

public class CinemaSystem {
    private UserManager userManager;
    private HallManager hallManager;
    private MovieManager movieManager;
    private ScheduleManager scheduleManager;
    private TicketManager ticketManager;
    private LogManager logManager;
    private Scanner scanner = new Scanner(System.in);
    private User currentUser;

    public CinemaSystem() {
        userManager = new UserManager();
        hallManager = new HallManager();
        movieManager = new MovieManager();
        scheduleManager = new ScheduleManager(hallManager, movieManager);
        ticketManager = new TicketManager(scheduleManager);
        logManager = new LogManager();
        // 初始化管理员账户
        userManager.initDefaultAdmin();
        // 初始化放映厅
        hallManager.initDefaultHalls();
    }

    public void run() {
        while (true) {
            System.out.println("\n==== 万东影院管理系统 ====");
            System.out.println("1. 登录");
            System.out.println("2. 退出");
            System.out.print("请选择: ");
            String choice = scanner.nextLine();
            if ("1".equals(choice)) {
                login();
            } else if ("2".equals(choice)) {
                System.out.println("感谢使用，再见！");
                break;
            } else {
                System.out.println("无效选择，请重试。");
            }
        }
    }

    private void login() {
        System.out.print("用户名: ");
        String username = scanner.nextLine();
        System.out.print("密码: ");
        String password = scanner.nextLine();
        User user = userManager.login(username, password);
        if (user == null) {
            System.out.println("用户名或密码错误。");
            return;
        }
        currentUser = user;
        if (user.getUserType().equals("管理员")) {
            adminMenu();
        } else if (user.getUserType().equals("经理")) {
            managerMenu();
        } else if (user.getUserType().equals("前台")) {
            frontDeskMenu();
        }
    }

    private void adminMenu() {
        while (true) {
            System.out.println("\n[管理员菜单]");
            System.out.println("1. 用户管理");
            System.out.println("2. 影厅管理");
            System.out.println("3. 查看日志");
            System.out.println("4. 注销登录");
            System.out.print("请选择: ");
            String choice = scanner.nextLine();
            if ("1".equals(choice)) {
                userManageMenu();
            } else if ("2".equals(choice)) {
                hallManageMenu();
            } else if ("3".equals(choice)) {
                viewLogMenu();
            } else if ("4".equals(choice)) {
                currentUser = null;
                break;
            } else {
                System.out.println("无效选择，请重试。");
            }
        }
    }

    private void userManageMenu() {
        while (true) {
            System.out.println("\n[用户管理]");
            System.out.println("1. 注册用户");
            System.out.println("2. 删除用户");
            System.out.println("3. 查询用户");
            System.out.println("4. 修改用户");
            System.out.println("5. 返回上级菜单");
            System.out.print("请选择: ");
            String choice = scanner.nextLine();
            try {
                if ("1".equals(choice)) {
                    System.out.print("用户类型（经理/前台）: ");
                    String type = scanner.nextLine();
                    System.out.print("用户名: ");
                    String username = scanner.nextLine();
                    System.out.print("密码: ");
                    String pwd = scanner.nextLine();
                    System.out.print("手机号: ");
                    String phone = scanner.nextLine();
                    userManager.register(type, username, pwd, phone);
                    System.out.println("注册成功");
                } else if ("2".equals(choice)) {
                    System.out.print("用户名: ");
                    String username = scanner.nextLine();
                    if (userManager.deleteUser(username)) {
                        System.out.println("删除成功");
                    } else {
                        System.out.println("用户不存在");
                    }
                } else if ("3".equals(choice)) {
                    System.out.print("用户名: ");
                    String username = scanner.nextLine();
                    User user = userManager.findUserByUsername(username);
                    if (user != null) {
                        System.out.println("ID:" + user.getUserId() + ", 用户名:" + user.getUsername() + ", 类型:" + user.getUserType() + ", 手机:" + user.getPhone());
                    } else {
                        System.out.println("用户不存在");
                    }
                } else if ("4".equals(choice)) {
                    System.out.print("用户名: ");
                    String username = scanner.nextLine();
                    System.out.print("新密码(可空): ");
                    String pwd = scanner.nextLine();
                    System.out.print("新手机号(可空): ");
                    String phone = scanner.nextLine();
                    if (userManager.updateUser(username, pwd, phone)) {
                        System.out.println("修改成功");
                    } else {
                        System.out.println("用户不存在");
                    }
                } else if ("5".equals(choice)) {
                    break;
                } else {
                    System.out.println("无效选择，请重试。");
                }
            } catch (Exception e) {
                System.out.println("操作失败: " + e.getMessage());
            }
        }
    }

    private void managerMenu() {
        while (true) {
            System.out.println("\n[经理菜单]");
            System.out.println("1. 电影管理");
            System.out.println("2. 场次管理");
            System.out.println("3. 注销登录");
            System.out.print("请选择: ");
            String choice = scanner.nextLine();
            if ("1".equals(choice)) {
                movieManageMenu();
            } else if ("2".equals(choice)) {
                scheduleManageMenu();
            } else if ("3".equals(choice)) {
                currentUser = null;
                break;
            } else {
                System.out.println("无效选择，请重试。");
            }
        }
    }

    private void movieManageMenu() {
        while (true) {
            System.out.println("\n[电影管理]");
            System.out.println("1. 添加电影");
            System.out.println("2. 删除电影");
            System.out.println("3. 查询电影");
            System.out.println("4. 列出所有电影");
            System.out.println("5. 返回上级菜单");
            System.out.print("请选择: ");
            String choice = scanner.nextLine();
            try {
                if ("1".equals(choice)) {
                    System.out.print("片名: ");
                    String name = scanner.nextLine();
                    System.out.print("导演: ");
                    String director = scanner.nextLine();
                    System.out.print("主演: ");
                    String mainActor = scanner.nextLine();
                    System.out.print("简介: ");
                    String desc = scanner.nextLine();
                    int duration = 0;
                    double rating = 0;
                    try {
                        System.out.print("时长(分钟): ");
                        duration = Integer.parseInt(scanner.nextLine());
                    } catch (Exception e) {
                        System.out.println("时长输入有误，请输入整数。");
                        continue;
                    }
                    try {
                        System.out.print("评分(0-10): ");
                        rating = Double.parseDouble(scanner.nextLine());
                    } catch (Exception e) {
                        System.out.println("评分输入有误，请输入数字。");
                        continue;
                    }
                    Movie movie = new Movie(name, director, mainActor, desc, duration, rating);
                    if (movieManager.addMovie(movie)) {
                        System.out.println("添加成功");
                    } else {
                        System.out.println("该电影已存在");
                    }
                } else if ("2".equals(choice)) {
                    System.out.print("片名: ");
                    String name = scanner.nextLine();
                    if (movieManager.removeMovie(name)) {
                        System.out.println("删除成功");
                    } else {
                        System.out.println("电影不存在");
                    }
                } else if ("3".equals(choice)) {
                    System.out.print("片名: ");
                    String name = scanner.nextLine();
                    Movie m = movieManager.findMovieByName(name);
                    if (m != null) {
                        System.out.println("片名:" + m.getName() + ", 导演:" + m.getDirector() + ", 主演:" + m.getMainActor() + ", 时长:" + m.getDuration() + ", 评分:" + m.getRating());
                    } else {
                        System.out.println("电影不存在");
                    }
                } else if ("4".equals(choice)) {
                    for (Movie m : movieManager.getMovies()) {
                        System.out.println("片名:" + m.getName() + ", 导演:" + m.getDirector() + ", 主演:" + m.getMainActor() + ", 时长:" + m.getDuration() + ", 评分:" + m.getRating());
                    }
                } else if ("5".equals(choice)) {
                    break;
                } else {
                    System.out.println("无效选择，请重试。");
                }
            } catch (Exception e) {
                System.out.println("操作失败: " + e.getMessage());
            }
        }
    }

    private void scheduleManageMenu() {
        while (true) {
            System.out.println("\n[场次管理]");
            System.out.println("1. 添加场次");
            System.out.println("2. 删除场次");
            System.out.println("3. 查询场次");
            System.out.println("4. 返回上级菜单");
            System.out.print("请选择: ");
            String choice = scanner.nextLine();
            try {
                if ("1".equals(choice)) {
                    System.out.print("场次编号: ");
                    String id = scanner.nextLine();
                    System.out.print("片名: ");
                    String movieName = scanner.nextLine();
                    Movie movie = movieManager.findMovieByName(movieName);
                    if (movie == null) {
                        System.out.println("电影不存在");
                        continue;
                    }
                    System.out.print("放映厅名: ");
                    String hallName = scanner.nextLine();
                    Hall hall = hallManager.findHallByName(hallName);
                    if (hall == null) {
                        System.out.println("放映厅不存在");
                        continue;
                    }
                    java.time.LocalDateTime time = null;
                    try {
                        System.out.print("开场时间(yyyy-MM-dd HH:mm): ");
                        String timeStr = scanner.nextLine();
                        time = java.time.LocalDateTime.parse(timeStr.replace(" ","T"));
                    } catch (Exception e) {
                        System.out.println("时间格式有误，请按 yyyy-MM-dd HH:mm 输入。");
                        continue;
                    }
                    double price = 0;
                    try {
                        System.out.print("票价: ");
                        price = Double.parseDouble(scanner.nextLine());
                    } catch (Exception e) {
                        System.out.println("票价输入有误，请输入数字。");
                        continue;
                    }
                    Schedule schedule = new Schedule(id, movie, hall, time, price);
                    if (scheduleManager.addSchedule(schedule)) {
                        System.out.println("添加成功");
                    } else {
                        System.out.println("该场次编号已存在");
                    }
                } else if ("2".equals(choice)) {
                    System.out.print("场次编号: ");
                    String id = scanner.nextLine();
                    if (scheduleManager.removeScheduleById(id)) {
                        System.out.println("删除成功");
                    } else {
                        System.out.println("场次不存在");
                    }
                } else if ("3".equals(choice)) {
                    System.out.print("片名(可空): ");
                    String movieName = scanner.nextLine();
                    if (movieName.isEmpty()) {
                        for (Schedule s : scheduleManager.getSchedules()) {
                            System.out.println("编号:" + s.getScheduleId() + ", 片名:" + s.getMovie().getName() + ", 厅:" + s.getHall().getName() + ", 时间:" + s.getStartTime() + ", 票价:" + s.getPrice());
                        }
                    } else {
                        for (Schedule s : scheduleManager.findSchedulesByMovieName(movieName)) {
                            System.out.println("编号:" + s.getScheduleId() + ", 片名:" + s.getMovie().getName() + ", 厅:" + s.getHall().getName() + ", 时间:" + s.getStartTime() + ", 票价:" + s.getPrice());
                        }
                    }
                } else if ("4".equals(choice)) {
                    break;
                } else {
                    System.out.println("无效选择，请重试。");
                }
            } catch (Exception e) {
                System.out.println("操作失败: " + e.getMessage());
            }
        }
    }

    private void frontDeskMenu() {
        while (true) {
            System.out.println("\n[前台菜单]");
            System.out.println("1. 售票");
            System.out.println("2. 退票");
            System.out.println("3. 查询场次");
            System.out.println("4. 注销登录");
            System.out.print("请选择: ");
            String choice = scanner.nextLine();
            try {
                if ("1".equals(choice)) {
                    System.out.print("场次编号: ");
                    String scheduleId = scanner.nextLine();
                    int count = 0;
                    try {
                        System.out.print("购票数量: ");
                        count = Integer.parseInt(scanner.nextLine());
                    } catch (Exception e) {
                        System.out.println("购票数量输入有误，请输入整数。");
                        continue;
                    }
                    List<int[]> seats = new ArrayList<>();
                    List<Boolean> isChildList = new ArrayList<>();
                    for (int i = 0; i < count; i++) {
                        int row = 0, seat = 0;
                        try {
                            System.out.print("第" + (i+1) + "张票-排号: ");
                            row = Integer.parseInt(scanner.nextLine());
                            System.out.print("第" + (i+1) + "张票-座号: ");
                            seat = Integer.parseInt(scanner.nextLine());
                        } catch (Exception e) {
                            System.out.println("排号或座号输入有误，请输入整数。");
                            i--;
                            continue;
                        }
                        System.out.print("是否儿童票(y/n): ");
                        String isChild = scanner.nextLine();
                        seats.add(new int[]{row, seat});
                        isChildList.add("y".equalsIgnoreCase(isChild));
                    }
                    List<Ticket> sold = ticketManager.sellTickets(scheduleId, seats, currentUser.getUsername(), isChildList);
                    double total = 0;
                    for (Ticket t : sold) {
                        total += t.getPrice();
                        System.out.println("出票成功: 片名:" + t.getSchedule().getMovie().getName() + ", 场次:" + t.getSchedule().getScheduleId() + ", 座位:" + t.getRow() + "排" + t.getSeatNumber() + "座, 票号:" + t.getTicketId() + ", 票价:" + t.getPrice() + (t.isChild()?"(儿童票)":""));
                    }
                    System.out.println("总金额: " + total);
                } else if ("2".equals(choice)) {
                    System.out.print("电子票号: ");
                    String ticketId = scanner.nextLine();
                    try {
                        double refund = ticketManager.refundTicket(ticketId);
                        System.out.println("退票成功，退还金额: " + refund);
                    } catch (Exception e) {
                        System.out.println("退票失败: " + e.getMessage());
                    }
                } else if ("3".equals(choice)) {
                    for (Schedule s : scheduleManager.getSchedules()) {
                        System.out.println("编号:" + s.getScheduleId() + ", 片名:" + s.getMovie().getName() + ", 厅:" + s.getHall().getName() + ", 时间:" + s.getStartTime() + ", 票价:" + s.getPrice());
                    }
                } else if ("4".equals(choice)) {
                    currentUser = null;
                    break;
                } else {
                    System.out.println("无效选择，请重试。");
                }
            } catch (Exception e) {
                System.out.println("操作失败: " + e.getMessage());
            }
        }
    }

    private void hallManageMenu() {
        while (true) {
            System.out.println("\n[影厅管理]");
            System.out.println("1. 添加影厅");
            System.out.println("2. 删除影厅");
            System.out.println("3. 查询影厅");
            System.out.println("4. 列出所有影厅");
            System.out.println("5. 返回上级菜单");
            System.out.print("请选择: ");
            String choice = scanner.nextLine();
            try {
                if ("1".equals(choice)) {
                    System.out.print("影厅名: ");
                    String name = scanner.nextLine();
                    int rows = 0, seatsPerRow = 0;
                    try {
                        System.out.print("行数: ");
                        rows = Integer.parseInt(scanner.nextLine());
                        System.out.print("每行座位数: ");
                        seatsPerRow = Integer.parseInt(scanner.nextLine());
                    } catch (Exception e) {
                        System.out.println("行数或座位数输入有误，请输入整数。");
                        continue;
                    }
                    Hall hall = new Hall(name, rows, seatsPerRow);
                    if (hallManager.addHall(hall)) {
                        System.out.println("添加成功");
                    } else {
                        System.out.println("该影厅已存在");
                    }
                } else if ("2".equals(choice)) {
                    System.out.print("影厅名: ");
                    String name = scanner.nextLine();
                    if (hallManager.removeHall(name)) {
                        System.out.println("删除成功");
                    } else {
                        System.out.println("影厅不存在");
                    }
                } else if ("3".equals(choice)) {
                    System.out.print("影厅名: ");
                    String name = scanner.nextLine();
                    Hall h = hallManager.findHallByName(name);
                    if (h != null) {
                        System.out.println("影厅:" + h.getName() + ", 行数:" + h.getRows() + ", 每行座位:" + h.getSeatsPerRow());
                    } else {
                        System.out.println("影厅不存在");
                    }
                } else if ("4".equals(choice)) {
                    for (Hall h : hallManager.getHalls()) {
                        System.out.println("影厅:" + h.getName() + ", 行数:" + h.getRows() + ", 每行座位:" + h.getSeatsPerRow());
                    }
                } else if ("5".equals(choice)) {
                    break;
                } else {
                    System.out.println("无效选择，请重试。");
                }
            } catch (Exception e) {
                System.out.println("操作失败: " + e.getMessage());
            }
        }
    }

    private void viewLogMenu() {
        System.out.println("\n[系统日志]");
        try (java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader("system.log"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            System.out.println("日志读取失败: " + e.getMessage());
        }
    }
} 